#include <func.h>
#include "head.h"

int recvFile(int netFd){
    train_t t;
    bzero(&t,sizeof(t));
    //先接收文件名长度
    int ret = recv(netFd,&t.dataLength,sizeof(t.dataLength),MSG_WAITALL);
    ERROR_CHECK(ret,-1,"recv nameLenght");
    //再接收文件名字
    ret = recv(netFd,t.buf,t.dataLength,MSG_WAITALL);
    ERROR_CHECK(ret,-1,"recv fileName");
    long fileSize;
    //获取描述文件总大小的火车头
    recv(netFd,&t.dataLength,sizeof(t.dataLength),MSG_WAITALL);
    ERROR_CHECK(ret,-1,"recv dataLength");
    //再获取文件总大小
    recv(netFd,&fileSize,t.dataLength,MSG_WAITALL);
    ERROR_CHECK(ret,-1,"recv fileSize");
    printf("目标文件大小: %ldM\n",fileSize/M);
    //打开或者创建临时文件
    int fd = open(t.buf,O_RDWR|O_CREAT,0666);
    ERROR_CHECK(fd,-1,"open");
    //获取临时文件总大小，并发送给发送端
    struct stat statbuf;
    ret = fstat(fd,&statbuf);
    ERROR_CHECK(ret,-1,"fstat");
    bzero(&t,sizeof(t));
    t.dataLength = sizeof(statbuf.st_size);
    //把文件大小放到小火车车厢中
    memcpy(t.buf,&statbuf.st_size,sizeof(statbuf.st_size));
    //再发送文件大小
    send(netFd,&t,sizeof(t.dataLength)+t.dataLength,MSG_NOSIGNAL);
    off_t downSize = statbuf.st_size;//当前已经下载文件的大小
    printf("当前文件大小:%ldM\n",downSize/M);
    off_t needSize = (fileSize - downSize)/M;//需下载的量
    printf("需下载:%ldM\n",needSize);
    off_t lastSize = statbuf.st_size;//在上一次完成下载文件总大小千分之一时的文件大小
    off_t slice = fileSize/1000;//总文件大小千分之一
    //设置当前文件偏移量，让其在之前数据之后读写
    if(statbuf.st_size != 0){
        lseek(fd,downSize,SEEK_SET);
    }
    //char bar[50] = {0};
    //int i = 0;
    //int count = 0;
    //char *lab="-\\|/";
    //当文件小于于100M
        while(1){
             bzero(&t,sizeof(t));
             ret = recv(netFd,&t.dataLength,sizeof(int),MSG_WAITALL);
             ERROR_CHECK(ret,-1,"recv dataLength");
             if(t.dataLength == 0){
                 break;
             }
             downSize += t.dataLength;
             if(downSize - lastSize > slice){
                 double precent = (double)downSize/fileSize;
                 printf("[%5.2lf%%]\r",100.0*precent);
                 fflush(stdout);
                // count++;
                // if(count >= 20){
                //     bar[i++] = '#';
                //     bar[i] = '\0';
                // }
                // lastSize = downSize;
             }
             ret = recv(netFd,t.buf,t.dataLength,MSG_WAITALL);
             ERROR_CHECK(ret,-1,"recv t.buf");
             write(fd,t.buf,t.dataLength);
        }
    printf("[100.00%s]\n","%");
    close(fd);
}